package com.fishery.base.service.impl;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fishery.base.entity.Catch;
import com.fishery.base.entity.vo.TraceCatchRecordVo;
import com.fishery.base.mapper.CatchMapper;
import com.fishery.base.service.CatchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;

@Service
public class CatchServiceImpl extends ServiceImpl<CatchMapper, Catch> implements CatchService {

	@Autowired
	private CatchMapper catchMapper;

	@Autowired
	private ExecutorService threadPool;

	@Override
	public Page<Catch> pageCatchRecords(String baseId, int size, int current) {
		Page<Catch> page = new Page<>(current, size);
		Future<List<Catch>> future = threadPool.submit(() ->
				catchMapper.selectCatchRecordsWithPage(baseId, (current - 1) * size, size));
		int total = catchMapper.selectTotal(baseId);
		page.setTotal(total);
		page.setPages(total / size + (total % size == 0 ? 0 : 1));
		try {
			page.setRecords(future.get());
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		return page;
	}

	@Override
	public boolean decrease(String id, Integer amount, Double weight) {
		try {
			return catchMapper.decreaseAmountAndWeight(id, amount, weight) > 0;
		} catch (Exception e) {
			return false;
		}
	}

	@Override
	public boolean increase(String id, Integer amount, Double weight) {
		return catchMapper.increaseAmountAndWeight(id, amount, weight) > 0;
	}

	@Override
	public TraceCatchRecordVo traceCatchRecordById(String id) {
		return catchMapper.findCatchRecordByIdEvenDelete(id);
	}

}
